package cn.gmcx.lazy.izze.controller;

import cn.gmcx.lazy.izze.exception.BizException;
import cn.gmcx.lazy.izze.pojo.User;
import cn.gmcx.lazy.izze.service.FileService;
import cn.gmcx.lazy.izze.service.IUserService;
import cn.gmcx.lazy.izze.utils.JwtUtils;
import cn.gmcx.lazy.izze.utils.Result;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUserService userService;

    @Autowired
    private FileService fileService;

    @PostMapping("/add_user")
    public Result addUser(@RequestParam("avatar") MultipartFile file,
                          @Valid @RequestPart("user") User user,
                          BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            throw new BizException(bindingResult.getFieldError().getDefaultMessage());
        }

        if (!file.isEmpty()) {
            String fileUrl = fileService.getImg_url(file);
            userService.add(fileUrl, user);
            return Result.success(fileUrl);
        } else {
            return Result.fail("文件上传失败");
        }
    }

    @PostMapping("/login_user")
    public Result login(@Valid @RequestBody User user,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            throw new BizException(bindingResult.getFieldError().getDefaultMessage());
        }
//       try {
           String token =  userService.select_user(user);
           return new Result(200,"登陆成功",token);
//       }catch (BizException e){
//           e.printStackTrace();
//           return Result.fail("登录失败");
//       }
    }

    @PostMapping("/return_id")
    public Result returnId(String token){
        DecodedJWT decodedJWT = JwtUtils.parseJwt(token);
        String id = decodedJWT.getClaim("id").asString();
        User user = userService.selectId(id);
        user.setPassword(null);
        return Result.success(user);
    }

}
